import { ResponseError } from './errors.js';

/**
 * @import {ServerResponseContent} from "./httpClient.js"
 */

// ===================== 常量定义 =====================

const SERVER_CODES = Object.freeze({
  SUCCESS: 0,
});

const MESSAGE_TYPES = Object.freeze({
  INFO: 'info',
  WARN: 'warn',
  ERROR: 'error',
  SUCCESS: 'success',
});

// ===================== 业务实现 =====================

/**
 * 显示消息
 * @param {'info'|'warn'|'error'|'success'|undefined} type - 消息类型
 * @param {string} message - 消息内容
 */
function showMessage(type, message) {
  const messageHandlers = {
    [MESSAGE_TYPES.INFO]: console.info,
    [MESSAGE_TYPES.WARN]: console.warn,
    [MESSAGE_TYPES.ERROR]: console.error,
    [MESSAGE_TYPES.SUCCESS]: console.log,
  };

  if (type && messageHandlers[type]) {
    messageHandlers[type](message);
  }
}

/**
 * 处理显示消息
 * @param {ServerResponseContent} content - 响应内容
 */
export function handleShowMessage(content) {
  // 消息提示处理
  if (content.msg && content.msgType) {
    showMessage(content.msgType, content.msg);
  }

  return content;
}

/**
 * 处理通用错误
 * @param {ServerResponseContent} content - 响应内容
 */
export function handleCommonError(content) {
  if (content.code !== SERVER_CODES.SUCCESS) throw new ResponseError('服务端响应');

  return content.data;
}


export const defaultHandlers = [handleShowMessage, handleCommonError];
